<template>
  <el-dialog
    :title="'编辑标签：' + mat.title"
    width="40%"
    :visible="visible" @update:visible="changeVisible($event)"
    append-to-body
  >
    <div class="edit-tags-pane">
      <div class="tag-cat-pane" v-for="(c, j) in cats" :key="j">
        <label class="cat-name">{{ catName(c) }}：</label>
        <tag
          v-for="(t, i) in catTags(c)"
          :tag="t"
          :key="i"
          :deletable="true"
          @delete-tag="deleteTag"
        ></tag>
        <span class="tag-input">
          <tag-input
            :cat="c"
            :kind="kind"
            :tags="tags"
            @select-tag="selectTag"
          ></tag-input>
        </span>
      </div>
    </div>

    <div class="toolbar">
      <el-button type="primary" @click="save">保存</el-button>
      <el-button @click="close">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import Tag from "./Tag.vue";
import TagInput from "./TagInput.vue";
import { TagCatNames, TagCatsForMatKind } from "@js/constants.js";
export default {
  props: ["tags", "kind", "mat", "visible"],
  components: {
    Tag,
    TagInput,
  },
  data() {
    return {
      editingTags: this.tags || [],
      cats: TagCatsForMatKind.get(this.kind)
    };
  },
  watch: {
    tags() {
      this.editingTags = this.tags || [];
    }
  },
  methods: {
    catTags(c) {
      return this.editingTags.filter((t) => t.cat == c);
    },
    catName(c) {
      if (TagCatNames.has(c)) {
        return TagCatNames.get(c);
      } else {
        return "未知标签";
      }
    },
    selectTag(t) {
      this.editingTags.push(t);
    },
    changeVisible(visible) {
      this.$emit('update:visible', visible);
    },
    close() {
      this.$emit('update:visible', false);
    },
    save() {
      let json = {
        mid: this.mat.id,
        tags: this.editingTags
      };
      this.authPost("/api/v1/tags/update", json).then(res => {
        console.log("update tags succ:", res.data);
        this.close();
      });
    },
    deleteTag(tag) {
      this.editingTags = this.editingTags.filter(t => t != tag);
    }
  },
};
</script>

<style lang="stylus">
.edit-tags-pane
  .tag-cat-pane
    margin-bottom 2vh

    .cat-name
      font-weight bold

    .el-input
      width 8vw

  .toolbar
    margin-top 4vh

  .tag-wrap
    margin-right 0.5vw
</style>